import csv
import json
import numpy as np
from sklearn.tree import DecisionTreeClassifier
import pandas as pd
from sklearn.ensemble import RandomForestClassifier  # 导入sklearn库的RandomForestClassifier函数
from sklearn.model_selection import train_test_split
from sklearn import metrics  # 分类结果评价函数
from sklearn.preprocessing import StandardScaler

# 函数需不需要返回转置要根据具体情况看
# 如果不转置每个label返回的就是一个行向量
# 这里转置了，每个label就是对应的列向量

train = pd.read_csv("../data/train.csv")
test_data = pd.read_csv("../data/pre_contest_test1.csv")

label = train['label']
train_data = train.drop(['label'], axis=1)

# 训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(train_data, label, random_state=0, train_size=0.8)

# 数据预处理
# x_train.fillna(x_train.mean())
# y_train.fillna(y_train.mean())
x_train = x_train.fillna(0)
y_train = y_train.fillna(0)
x_test = x_test.fillna(0)
y_test = y_test.fillna(0)

test_data = test_data.fillna(0)
# file = open("C:/Users/24029/Desktop/涂佳雪-重庆大学/train2.csv", mode='w')
# csv_writer = csv.writer(file)
# csv_writer.writerows(x_train)

# 数据标准化
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)
x_test = scaler.transform(x_test)

# 训练
model = RandomForestClassifier(n_estimators=50, criterion='entropy', random_state=42)
model.fit(x_train, y_train)
print(model)  # 输出模型RandomForestClassifier

# 在测试集上测试模型
expected = y_test  # 测试样本的期望输出
predicted = model.predict(x_test)  # 测试样本预测
probility = model.predict_proba(x_test)  # 概率


# 输出结果
print(metrics.classification_report(expected, predicted))  # 输出结果，精确度、召回率、f-1分数
print(metrics.confusion_matrix(expected, predicted))  # 混淆矩阵

auc = metrics.roc_auc_score(y_test, probility, multi_class='ovo')
accuracy = metrics.accuracy_score(y_test, predicted)  # 求精度
print("Accuracy: %.2f%%" % (accuracy * 100.0))

# write result
result = model.predict(test_data)

result_dict = {}

for i in range(len(result)):
    result_dict[str(i)] = int(result[i])

print(len(result))
print(result_dict)

json_object = json.dumps(result_dict, indent=4)
file = open("../data/submit.json", mode='w')
file.write(json_object)


